﻿using Gif.Components;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tool
{
    /// <summary>
    /// gif图像处理类
    /// 
    /// gif图像分解：    SaveSubImage()
    /// 合并为gif图像：  SaveToGif()
    /// </summary>
    public class GifTools
    {
        /// <summary>
        /// 自动处理函数;
        /// 获取所有gif图像的子图；
        /// 或合并所有图像为单个gif图像；
        /// </summary>
        public static void AutoProcess(string[] files)
        {
            List<string> gifList = new List<string>();
            List<string> picList = new List<string>();

            foreach (string file in files)
            {
                if(file.ToLower().EndsWith(".gif")) gifList.Add(file);
                else picList.Add(file);
            }

            // 获取所有gif的子图像
            foreach (string gif in gifList) GifTools.SaveSubImage(gif);

            // 合并所有图像为单个gif图像
            GifTools.SaveToGif(picList.ToArray());
        }

        /// <summary>
        /// 获取gif图像的所有子图像，保存到gifPath所在路径
        /// </summary>
        public static void SaveSubImage(string gifPath)
        {
            Image imgGif = Image.FromFile(gifPath, true);
            SaveSubImage(imgGif, gifPath);

            imgGif.Dispose();
        }

        /// <summary>
        /// 获取imgGif的所有子图像,保存到savePath对应的路径
        /// </summary>
        public static void SaveSubImage(Image imgGif, string savePath)
        {
            //Create a new FrameDimension object from this image
            var ImgFrmDim = new FrameDimension(imgGif.FrameDimensionsList[0]);

            //Determine the number of frames in the image
            //Note that all images contain at least 1 frame,
            //but an animated GIF will contain more than 1 frame.
            int n = imgGif.GetFrameCount(ImgFrmDim);    // 获取子图像数目

            // Save every frame into png format file
            for (int i = 0; i < n; i++)
            {
                imgGif.SelectActiveFrame(ImgFrmDim, i); // 选择子图

                string newName = savePath;
                if (newName.Contains(".")) newName = newName.Substring(0, newName.LastIndexOf("."));
                newName =  newName + "_" + i + ".png";

                imgGif.Save(newName, ImageFormat.Png);  // 保存
            }
        }

        /// <summary>
        /// 保存多张图像为单张gif图像
        /// </summary>
        public static void SaveToGif(string[] imagePaths, string outputFilePath="", int ms = 100, bool repet = true)
        {
            List<Image> list = new List<Image>();
            foreach (string path in imagePaths)
            {
                list.Add(Image.FromFile(path));
            }

            if (outputFilePath.Equals(""))
            {
                // 设置输出文件名
                outputFilePath = imagePaths[0];
                if (outputFilePath.Contains(".")) outputFilePath = outputFilePath.Substring(0, outputFilePath.LastIndexOf("."));
                outputFilePath = outputFilePath + ".gif";
            }

            SaveToGif(list.ToArray(), outputFilePath, ms, repet);
            foreach (Image image in list) image.Dispose();
        }

        /// <summary>
        /// 保存多张图像为单张gif图像
        /// </summary>
        public static void SaveToGif(Image[] images, string outputFilePath, int ms = 100, bool repet = true)
        {
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.Start(outputFilePath);      // 输出gif文件路径
            encoder.SetDelay(ms);               // 帧间隔
            encoder.SetRepeat(repet ? 0 : -1);  // 0:循环 -1:不循环
            for (int i = 0, count = images.Length; i < count; i++)
            {
                encoder.AddFrame(images[i]);    // 添加图像
            }
            encoder.Finish();
        }
    }
}
